package demo.java.lang.management.jvm;

import com.sun.management.OperatingSystemMXBean;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.lang.management.RuntimeMXBean;

/**
 * 收集进程cpu使用率
 */
public class CpuRateCollector {

    private static final Logger logger = LoggerFactory.getLogger(CpuRateCollector.class);

    private OperatingSystemMXBean OperatingSystem;
    private RuntimeMXBean Runtime;

    private volatile long lastCPUTime;
    private volatile long lastCPUUpTime;


    public CpuRateCollector(OperatingSystemMXBean OperatingSystem, RuntimeMXBean Runtime){
        this.OperatingSystem = OperatingSystem;
        this.Runtime = Runtime;
        try {
            // 初始化
            lastCPUTime = getProcessCpuTime();
        } catch (Exception e) {
            logger.error("CpuRateCollector static block:"+e.getMessage(), e);
        }
    }

    private long getProcessCpuTime() {
        return this.OperatingSystem.getProcessCpuTime();
    }

    private long getUpTime() {
        return this.Runtime.getUptime();
    }

    public double collect() {
        try {
            long cpuTime = getProcessCpuTime();
            long upTime = getUpTime();

            long elapsedCpu = cpuTime - lastCPUTime;
            long elapsedTime = upTime - lastCPUUpTime;

            lastCPUTime = cpuTime;
            lastCPUUpTime = upTime;

            if (elapsedTime <= 0) {
                return 0d;
            }
            double cpuUsage = elapsedCpu / (elapsedTime * 10000F);

            return JVMUtils.formatDouble(cpuUsage);
        }catch (Throwable e){
            logger.error("CpuRateCollector collect error, {}", e.getMessage());
            return 0d;
        }
    }

}
